package edu.hawaii.halealohacli.command; 

import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.source.jaxb.Source;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Requests for the energyGenerated yesterday.
 * @author Russell Vea for ICS 314 Fall 2011.
 * @author Branden Ogata
 */
public class DailyEnergy implements Command {

  private double energy =  0.0;  
  
  /**
   * Connects to a WattDepot server and prints the results of the daily-energy command.
   * 
   * @param client a WattDepot client
   * @param source the source to query
   * @param days the first being the timestamp for the day to query
   * @throws Exception on an error with the Server
   */
  public void printResults(WattDepotClient client, 
                           Source source, XMLGregorianCalendar... days) throws Exception {
    if (client.isHealthy()) {
      System.out.format("Connected successfully to: %s%n", client);
    }
    else {
      System.out.format("Could not connect to: %s%n", client);
      return;
    }
    XMLGregorianCalendar dayEnd = (XMLGregorianCalendar) days[0].clone();
    dayEnd = Tstamp.incrementDays(dayEnd, 1);

    String sourceName = source.getName();
    try { 
      this.energy = client.getEnergyConsumed(sourceName, days[0], dayEnd, 15) / 1000;
    }
    catch (MiscClientException e) {
      throw new Exception(e);
    }
    
    System.out.format("%s \t\t %f kWh consumed on %tD \n", 
                      sourceName, this.energy, days[0].toGregorianCalendar());
  }
  
  /**  
   * Returns the value from the last daily-energy command.
   * 
   * @return this.energy for testing purposes.   
   * 
   */
  public double getEnergy() {
    return this.energy;
  }
}
